package com.github.wxiaoqi.security.biz.modules.pay.biz;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.biz.feign.CrmFeign;
import com.github.wxiaoqi.security.biz.feign.MallFeign;
import com.github.wxiaoqi.security.biz.modules.aisuan.entity.AisuanRecord;
import com.github.wxiaoqi.security.biz.modules.aisuan.mapper.AisuanRecordMapper;
import com.github.wxiaoqi.security.biz.modules.fightGroup.biz.FightGroupInfoBiz;
import com.github.wxiaoqi.security.biz.modules.fightGroup.entity.FightGroupOrder;
import com.github.wxiaoqi.security.biz.modules.fightGroup.mapper.FightGroupOrderMapper;
import com.github.wxiaoqi.security.biz.modules.pay.entity.CmsPayOrder;
import com.github.wxiaoqi.security.biz.modules.pay.mapper.CmsPayOrderMapper;
import com.github.wxiaoqi.security.biz.modules.refund.biz.RefundBiz;
import com.github.wxiaoqi.security.biz.modules.restaurant.biz.RestaurantShoppingCartInfoBiz;
import com.github.wxiaoqi.security.biz.modules.restaurant.entity.RestaurantOrderInfo;
import com.github.wxiaoqi.security.biz.modules.restaurant.mapper.RestaurantOrderInfoMapper;
import com.github.wxiaoqi.security.common.enums.CustomerTypeEnums;

/**
 * 支付回调处理
 * @author he
 *
 */
@Service
public class PayCallBackBiz {

	private static final Logger logger = (Logger) LoggerFactory.getLogger(PayCallBackBiz.class);

	@Autowired
	private CrmFeign crmFeign;
	@Autowired
	private MallFeign mallFeign;
	@Autowired
	private CmsPayOrderMapper cmsPayOrderMapper;
	@Autowired
	private RefundBiz refundBiz;
	@Autowired
	private FightGroupOrderMapper fightGroupOrderMapper;
	@Autowired
	private RestaurantOrderInfoMapper restaurantOrderInfoMapper;
	@Autowired
	private FightGroupInfoBiz fightGroupInfoBiz;
	@Autowired
	private RestaurantShoppingCartInfoBiz restaurantShoppingCartInfoBiz;
	@Autowired
	private AisuanRecordMapper aisuanRecordMapper;

	/**
	 * 支付完成回调
	 * @param request
	 * @return
	 */
	public void payCallBack(Map<String, Object> params){
		logger.info("支付完成回调开始.......{}",params);
		String platformId = (String) params.get("platformId");
		String orderNo = (String) params.get("orderNo");
		String txStatus = (String) params.get("txStatus");
		String amount = (String) params.get("amount");
		BigDecimal amountDecimal = new BigDecimal(amount);
		CmsPayOrder cmsScenesOrder = new CmsPayOrder();
		cmsScenesOrder.setPlatformId(platformId);
		cmsScenesOrder.setPayOrderNo(orderNo);
		CmsPayOrder selectCmsPayOrder = cmsPayOrderMapper.selectOne(cmsScenesOrder);
		if(null == selectCmsPayOrder){
			logger.info("支付完成回调-订单不存在.......");
			return;
		}
		if(0 != selectCmsPayOrder.getTxAmt().compareTo(amountDecimal)){
			logger.info("支付完成回调-金额不一致.......");
			return;
		}

		//支付成功入账，更新订单状态
		if("00".equals(txStatus)){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("platformId", (String) params.get("platformId"));
			map.put("orderNo", (String) params.get("orderNo"));
			map.put("intoAccAmt", (String) params.get("amount"));
			map.put("merchantId", selectCmsPayOrder.getMerchantId());
			map.put("merchantType", "CUST01");
			if("1".equals(selectCmsPayOrder.getPayCode())){//支付
				map.put("accountType", "ACC001");
				map.put("customerType", CustomerTypeEnums.mer_user.getCode());
				map.put("tradeType", "01");//支付
			}else if("2".equals(selectCmsPayOrder.getPayCode())){//充值
				map.put("personalId", selectCmsPayOrder.getPersonalId());
				map.put("accountType", "ACC011");
				map.put("customerType", CustomerTypeEnums.per_user.getCode());
				map.put("tradeType", "04");//充值
			}
			crmFeign.inAccounting(map);
			selectCmsPayOrder.setTxStatus("00");//支付成功
		}else{
			selectCmsPayOrder.setTxStatus("01");//支付失败
		}
		cmsPayOrderMapper.updateByPrimaryKey(selectCmsPayOrder);

		//更新场景订单
		String scenesCode = selectCmsPayOrder.getScenesCode();
		params.put("scenesCode", scenesCode);
		if("4".equals(scenesCode)){
			//竞拍 不存在第三方支付
		}else if("5".equals(scenesCode) || "6".equals(scenesCode)){
			//拼团参团//拼团创建团
			this.updateFightGroupOrder(params, selectCmsPayOrder);
		}else if("3".equals(scenesCode) || "2".equals(scenesCode) || "1".equals(scenesCode)){
			//店内点餐//预订点餐//外卖
			this.updateOrderDishesOrder(params, selectCmsPayOrder);
		}else if ("8".equals(scenesCode)) {
			//商城
			params.put("payOrderNo", orderNo);
			this.updateMallOrder(params);
		}else if("10".equals(scenesCode)){
			//爱算
			logger.info("进入爱算回调修改场景订单状态");
			this.updateAisuanOrder(params);
		}
		logger.info("支付完成回调结束.......");
	}
	/**
	 * 修改爱算支付完成状态
	 * 用户付多少钱直接付给平台方--给平台方展示金额，先不判断金额是否一致
	 */
	private void updateAisuanOrder(Map<String, Object> params){
		logger.info("修改爱算支付完成状态--传入参数{}", params);
		String txStatus = (String) params.get("txStatus");
		String orderNo = (String) params.get("orderNo");
		String amount = (String) params.get("amount");
		AisuanRecord record = new AisuanRecord();
		record.setPayOrderNo(orderNo);
		List<AisuanRecord> list = aisuanRecordMapper.select(record);
		
		if(list.size() == 0){
			logger.info("修改爱算支付完成状态 --未查询到记录");
			return;
		}
		AisuanRecord re = list.get(0);
		re.setAmt(amount);
		logger.info("修改爱算支付完成状态 --txStatus--{}",txStatus);
		if(null != txStatus){
			if("00".equals(txStatus)){
				logger.info("修改爱算支付完成状态 --成功");
				//成功
				re.setPayStatus(1);
			}else{
				logger.info("修改爱算支付完成状态 --失败");
				//失败
				re.setPayStatus(3);
			}
		}
		aisuanRecordMapper.updateByPrimaryKey(re);
		logger.info("修改爱算订单状态。。。{}"+record.toString());
	}
	private void updateMallOrder(Map<String, Object> params){
		String txStatus = (String) params.get("txStatus");
		if(null != txStatus){
			if("00".equals(txStatus)){
				params.put("txStatus", "00");//退款成功
			}else{
				params.put("txStatus", "02");//退款失败
			}
		}
		Map<String, Object> respMap = mallFeign.updatePayOrder(params);
		logger.info("修改商城订单状态。。。{}"+respMap);
	}
	
	private void updateAisuanRecord(Map<String, Object> params){
		AisuanRecord record = new AisuanRecord();
		//record.setPlatformId((String) params.get("platformId"));
		record.setPlatformId((Long)params.get("platformId"));
		//record.setPayOrderNo((Long) params.get("orderNo"));
	}
	/**
	 * 拼团订单处理
	 * @param params
	 */
	private void updateFightGroupOrder(Map<String, Object> params, CmsPayOrder cmsScenesOrder){
		//根据订单号查询竞拍订单
		FightGroupOrder fightGroupOrder = new FightGroupOrder();
		fightGroupOrder.setPlatformId((String) params.get("platformId"));
		fightGroupOrder.setPayOrderNo((String) params.get("orderNo"));
		FightGroupOrder selectFightGroupOrder = fightGroupOrderMapper.selectOne(fightGroupOrder);
		if(null != selectFightGroupOrder){
			if("00".equals((String) params.get("txStatus"))){
				selectFightGroupOrder.setStatus("00");//支付成功
			}else{
				selectFightGroupOrder.setStatus("01");//支付失败
			}
			fightGroupOrderMapper.updateByPrimaryKey(selectFightGroupOrder);
		}
		//处理业务逻辑
		String extMap = cmsScenesOrder.getExtMap();
		JSONObject jsonExtMap = (JSONObject) JSONObject.parse(extMap);
		Map<String, Object> request = new HashMap<String, Object>();
		request.put("platformId", (String) params.get("platformId"));
		request.put("merchantId", cmsScenesOrder.getMerchantId());
		request.put("customerId", cmsScenesOrder.getCustomerId());
		request.put("goodsId", jsonExtMap.get("goodsId"));
		request.put("name", jsonExtMap.get("nickName"));
		request.put("userHeadPortrait", jsonExtMap.get("avatarUrl"));
		if("5".equals((String) params.get("scenesCode"))){//拼团参团
			request.put("groupId", jsonExtMap.get("groupId"));
			fightGroupInfoBiz.joinGroup(request);
		}else if("6".equals((String) params.get("scenesCode"))){//拼团创建团
			request.put("groupsId", jsonExtMap.get("groupsId"));
			request.put("payOrderNo", cmsScenesOrder.getPayOrderNo());
			fightGroupInfoBiz.createGroup(request);
		}
	}
	
	/**
	 * 点餐订单处理
	 * @param params
	 */
	private void updateOrderDishesOrder(Map<String, Object> params, CmsPayOrder cmsScenesOrder){
		RestaurantOrderInfo restaurantOrderInfo = new RestaurantOrderInfo();
		restaurantOrderInfo.setPlatformId((String) params.get("platformId"));
		restaurantOrderInfo.setPayOrderNo((String) params.get("orderNo"));
		RestaurantOrderInfo selectRestaurantOrderInfo = restaurantOrderInfoMapper.selectOne(restaurantOrderInfo);
		if(null != selectRestaurantOrderInfo){
			if("00".equals((String) params.get("txStatus"))){
				selectRestaurantOrderInfo.setStatus("00");//支付成功
			}else{
				selectRestaurantOrderInfo.setStatus("01");//支付失败
			}
			restaurantOrderInfoMapper.updateByPrimaryKey(selectRestaurantOrderInfo);
		}
		//处理业务逻辑
		String extMap = cmsScenesOrder.getExtMap();
		JSONObject jsonExtMap = (JSONObject) JSONObject.parse(extMap);
		Map<String, Object> request = new HashMap<String, Object>();
		request.put("platformId", (String) params.get("platformId"));
		request.put("merchantId", cmsScenesOrder.getMerchantId());
		if("3".equals((String) params.get("scenesCode"))){//店内点餐
			request.put("tableId", jsonExtMap.get("tableId"));
			restaurantShoppingCartInfoBiz.orderPayUpdate(request);
		}else if("2".equals((String) params.get("scenesCode"))){//预订点餐
			request.put("customerId", cmsScenesOrder.getCustomerId());
			request.put("type", "3");
			restaurantShoppingCartInfoBiz.reservationPayUpdate(request);
		}else if("1".equals((String) params.get("scenesCode"))){//外卖
			request.put("customerId", cmsScenesOrder.getCustomerId());
			request.put("type", "2");
			restaurantShoppingCartInfoBiz.reservationPayUpdate(request);
		}
	}

}
